
set(bindir "@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_BINDIR@")
set(libdir "@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_LIBDIR@")
message(STATUS "Editing RPATH of Moco dependency libraries")

macro(install_name_tool_change lib dep_name dep_oldpath)
    execute_process(COMMAND install_name_tool
            -change ${dep_oldpath}/lib${dep_name}.dylib
            @rpath/lib${dep_name}.dylib
            "${libdir}/lib${lib}.dylib")
endmacro()

macro(install_name_tool_id lib)
    execute_process(COMMAND install_name_tool
            -id @rpath/lib${lib}.dylib
            "${libdir}/lib${lib}.dylib")
endmacro()

macro(install_name_tool_add_rpath lib)
    execute_process(COMMAND install_name_tool
            -add_rpath "@loader_path/"
            "${libdir}/lib${lib}.dylib")
endmacro()

macro(install_name_tool_delete_rpath lib rpath)
    execute_process(COMMAND install_name_tool
            -delete_rpath ${rpath}
            "${libdir}/lib${lib}.dylib")
endmacro()

macro(install_name_tool_change_gfortran lib)
    execute_process(COMMAND bash "-c"
        "otool -L ${libdir}/lib${lib}.dylib | grep 'libgfortran.*version' | perl -pe 's/^\\s+(.*)\\/libg.*/\\1/gc'"
        OUTPUT_VARIABLE libgfortran_dir
        OUTPUT_STRIP_TRAILING_WHITESPACE)
    execute_process(COMMAND bash "-c"
        "otool -L ${libdir}/lib${lib}.dylib | grep 'libgfortran.*version' | perl -pe 's/.*lib(.*).dylib.*/\\1/gc'"
        OUTPUT_VARIABLE libgfortran_name
        OUTPUT_STRIP_TRAILING_WHITESPACE)
    install_name_tool_change(${lib} "${libgfortran_name}" "${libgfortran_dir}")
endmacro()

macro(install_name_tool_change_quadmath lib)
execute_process(COMMAND bash "-c"
    "otool -L ${libdir}/lib${lib}.dylib | grep 'libquadmath' | perl -pe 's/^\\s+(.*)\\/libq.*/\\1/gc'"
    OUTPUT_VARIABLE libquadmath_dir
    OUTPUT_STRIP_TRAILING_WHITESPACE)

execute_process(COMMAND bash "-c"
    "otool -L ${libdir}/lib${lib}.dylib | grep 'libquadmath' | perl -pe 's/.*lib(.*).dylib.*/\\1/gc'"
    OUTPUT_VARIABLE libquadmath_name
    OUTPUT_STRIP_TRAILING_WHITESPACE)
    install_name_tool_change(${lib} "${libquadmath_name}" "${libquadmath_dir}")
endmacro()


if (OPENSIM_WITH_CASADI)
    install_name_tool_add_rpath(casadi.3.7)
    install_name_tool_delete_rpath(casadi.3.7 "@CASADI_LIBDIR@")
    install_name_tool_delete_rpath(casadi_nlpsol_ipopt.3.7 "@CASADI_LIBDIR@")

    install_name_tool_add_rpath(ipopt.3)
    install_name_tool_add_rpath(coinmumps.3)
    install_name_tool_change(ipopt.3 coinmumps.3 "@IPOPT_LIBDIR@")

    install_name_tool_change(casadi_nlpsol_ipopt.3.7 ipopt.3 "@IPOPT_LIBDIR@")
    install_name_tool_change(casadi_nlpsol_ipopt.3.7 coinmumps.3 "@IPOPT_LIBDIR@")
    install_name_tool_change(casadi_nlpsol_ipopt.3.7 metis "@IPOPT_LIBDIR@")
    install_name_tool_change_gfortran(casadi_nlpsol_ipopt.3.7)
    install_name_tool_change_quadmath(casadi_nlpsol_ipopt.3.7)
    install_name_tool_add_rpath(casadi_nlpsol_ipopt.3.7)

endif()


